<template>
  <page-meta :root-font-size="rootFontSize() + 'px'"></page-meta>

  <view class="page-container">
    <customHeader title="奶酪口语体验营" :border-line="false" />

    <view class="container" :style="{ top: height }" v-if="dayDatas">
      <view class="course-table">
        <view class="day-info-container">
          <view class="stage" :style="{ '--progress': `${(serverDayIndex / 3) * 100}%` }" v-if="dayDatas"></view>
          <view class="day-info" v-for="(item, index) in dayDatas" :key="index" @click="doChangeDay(index)">
            <view class="day-progress" :style="{ '--progress': dayProgress(index) }">
              <view class="day-selected" v-if="selectedDayIndex === index"></view>
              <view class="day-progress-content">
                <view :class="['day', selectedDayIndex === index && 'active']">Day{{ index + 1 }}</view>
                <view :class="['progress', selectedDayIndex === index && 'active']">{{ dayProgressDes(index) }}</view>
              </view>
            </view>
            <view class="course-title">
              {{ item.title }}
            </view>
          </view>
        </view>
        <text class="des">本次体验营课程分<text style="color: #de4235">4</text>天，跟着专属老师一起循序渐进学习吧~</text>

        <image class="add-teacher" @click="handleAddTeacher"
          src="https://rwstatic.tentons.cn/web/Lesson/images/add-teacher-icon.png" />
      </view>
      <view class="course-list-header">
        <text class="current-day">Day{{ selectedDayIndex + 1 }}</text>
        <text class="current-progress">进度 {{ currentProgress }}</text>
      </view>
      <view class="course-list-container">
        <view class="course-container" v-for="(item, index) in selectedDayCourseInfos" :key="index">
          <text class="course-title">{{ item.sub_title }}</text>
          <text class="course-index">{{ item.lesson }}</text>
          <image v-if="item.process === -1" class="course-lock"
            src="https://rwstatic.tentons.cn/web/Lesson/images/lock-icon.png" />
          <view v-else
            :class="['course-status', item.process > 0 ? item.process === 100 ? 'finish' : 'learn' : 'start']"
            @click="doStartLearn(item)">
            {{ item.process > 0 ? item.process === 100 ? "已学完" : `${item.process}%` : "开始学习" }}
          </view>
        </view>
      </view>

      <button v-if="isShowDayReport" class="operate-button" @click="handleToDayReport">
        {{ selectedDayIndex !== 3 ? `我的Day${currentDayCourse.day_num}报告` : '毕业档案' }}
        <image class="operate-button-right" src="https://rwstatic.tentons.cn/web/Lesson/images/button-right-icon.png" />
      </button>
    </view>
  </view>

  <basePopup :isVisible="addVisible">
    <view class="add-teacher-container">
      <image class="teacher-header" src="https://rwstatic.tentons.cn/web/Lesson/images/add-teacher-header.png" />
      <view class="teacher-content">
        <view class="teacher-line"></view>
        <image class="teacher-qrcode" show-menu-by-longpress :src="teacherQrcode" />
        <text class="teacher-label">为确保课程成功激活</text>
        <text class="teacher-label">请长按识别二维码添加老师</text>
      </view>
      <view class="teacher-quit" @click="addVisible = false;">暂时跳过</view>
    </view>
  </basePopup>

  <CwCommon />
</template>

<script setup lang="ts">
import { onMounted, ref, computed, nextTick } from "vue";
import {rootFontSize, util} from "@/utils/util";
import basePopup from "@/components/basePopup.vue";
import API from "@/api";
import { onLoad, onShow } from '@dcloudio/uni-app';
import { handleNavigateTo } from "@/pages/lowPricedCourse/trialCourseHome/index";
import { getAnyApp } from "@/common/hooks";
import { useStore } from "vuex";

const store = useStore();
const { Cheese } = getAnyApp();

export interface IDay_course {
  data_id: number;
  data_type: number;
  process: number;
  title: string;
  sub_title: string;
  lesson: string;
  day_num: string;
  [x: string]: any;
}

interface IDayTitle {
  day_num: number;
  show_course: number;
  title: string;
  day_course: IDay_course[];
}

const height = ref(getApp().globalData!.pageTop);

const course_id = ref(0);
const dayDatas = ref<IDayTitle[]>([]);
const selectedDayIndex = ref(0); // 当前选择的第几天的索引
const serverDayIndex = ref(0); // 开课后的第几天
const addVisible = ref(false);
const teacherQrcode = ref("");
const currentSelDayIndex = ref(-1); // dang

onShow(async () => {
  const result = (await API.trialCourseHome({})) as any;

  if (Array.isArray(result) && !result.length) {
    return;
  }

  dayDatas.value = result.dayTitle;
  course_id.value = result.course_id;

  for (var i = 0; i < dayDatas.value.length; i++) {
    if (dayDatas.value[i].day_num === result.day_num) {
      serverDayIndex.value = i;
      break;
    }
  }

  if (currentSelDayIndex.value === -1) {
    selectedDayIndex.value = serverDayIndex.value;
  }

  store.dispatch("setCourseId", result.course_id);
  handleSetCourseMap(result.dayTitle);
});

const isShowDayReport = computed(() => {
  return dayDatas.value[selectedDayIndex.value]?.day_course.every(item => item.process === 100);
})

const currentDayCourse = computed(() => {
  return dayDatas.value[selectedDayIndex.value];
})

const currentProgress = computed(() => {
  let courses: IDay_course[] = dayDatas.value[selectedDayIndex.value]?.day_course;
  let completeCount = 0;

  if (Array.isArray(courses) && courses.length) {
    for (var i = 0; i < courses.length; i++) {
      if (courses[i].process === 100) {
        completeCount++;
      }
    }
    return `${completeCount}/${courses.length}`;
  } else {
    return "0/0";
  }
});

const selectedDayCourseInfos = computed(() => {
  let courses: IDay_course[] = dayDatas.value[selectedDayIndex.value]?.day_course;
  return courses;
});

const handleSetCourseMap = (data: IDayTitle[]) => {
  let courseMap = new Map();

  const findNextLesson = (dayCourse: IDay_course[], curId: string) => {
    const currentIndex = dayCourse.findIndex(item => item.id == curId);

    if (currentIndex === -1 || currentIndex === dayCourse.length - 1) {
      return {
        next_day_num: dayCourse[currentIndex].day_num,
        next_free_talk_id: -1,
        next_speak_skill_id: -1,
        next_lesson_data_id: -1,
        next_lesson_data_type: -1,
      }
    }

    return {
      next_lesson_data_id: dayCourse[currentIndex + 1].id,
      next_lesson_data_type: dayCourse[currentIndex + 1].data_type,
      next_day_num: dayCourse[currentIndex + 1].day_num,
      next_free_talk_id: dayCourse[currentIndex + 1].free_talk_id || -1,
      next_speak_skill_id: dayCourse[currentIndex + 1].speak_skill_id || -1,
    }
  }

  data.forEach(item => {
    item.day_course.forEach(val => {
      const { next_day_num, next_lesson_data_id, next_lesson_data_type, next_free_talk_id, next_speak_skill_id } = findNextLesson(item.day_course, val.id);

      courseMap.set(val.data_id, {
        course_id: course_id.value,
        day_num: val.day_num,
        data_id: val.data_id,
        data_type: val.data_type,
        free_talk_id: val.free_talk_id || -1,
        speak_skill_id: val.speak_skill_id || -1,
        next_day_num,
        next_lesson_data_id,
        next_lesson_data_type,
        next_free_talk_id,
        next_speak_skill_id,
      })
    })
  });

  uni.setStorageSync("lowCourseMap", JSON.stringify(Array.from(courseMap)));
}

const doChangeDay = (index: number) => {
  if (index > serverDayIndex.value) return util.showDialogue("课程暂未解锁~", 1000);
  selectedDayIndex.value = index;
  currentSelDayIndex.value = index;
};

const doStartLearn = async (item: any) => {
  console.log("item", item);
  console.log(`开始学习: ${item.sub_title} 进度:${item.process}% 类型:${item.data_type}`);

  if (item.process === -1) {
    return;
  }
  if (item.data_type === 9) {
    uni.navigateTo({
      url: `/pages/home/freeTalk/index?free_talk_id=${item.free_talk_id}&process=${item.process}`
    });
  } else if (item.data_type === 11) {
    uni.navigateTo({
      url: `/pages/lowPricedCourse/trialCourseHome/courseList/index?section_id=${item.data_id}&header_title=${item.sub_title}`,
    });
  } else {
    await handleNavigateTo(item);
  }
};

const dayProgress = (dayIndex: number) => {
  let courses: IDay_course[] = dayDatas.value[dayIndex]?.day_course;
  let completeCount = 0;

  for (var i = 0; i < courses.length; i++) {
    if (courses[i].process === 100) {
      completeCount++;
    }
  }
  return `${(completeCount / courses.length) * 100 + 0.01}%`;
};

const dayProgressDes = (dayIndex: number) => {
  let courses: IDay_course[] = dayDatas.value[dayIndex]?.day_course;
  let completeCount = 0;

  for (var i = 0; i < courses.length; i++) {
    if (courses[i].process === 100) {
      completeCount++;
    }
  }
  return `${completeCount}/${courses.length}`;
};

const handleToDayReport = async () => {
  let result: any;
  let pages = "";
  if (selectedDayIndex.value !== 3) {
    result = await API.shareDailyResult({
      course_id: course_id.value,
      day_num: currentDayCourse.value.day_num,
    });
    pages = "/pages/lowPricedCourse/situationalDialog/scoreReport/index";
  } else {
    result = await API.finishResult({
      course_id: course_id.value,
    });
    pages = "/pages/lowPricedCourse/situationalDialog/shareDiploma/index";
  }
  await Cheese.User?.setUserInfo(false);
  const temp = Object.assign(result, Cheese.User?.USERINFO, {
    course_id: course_id.value,
    day_num: currentDayCourse.value.day_num,
  });
  uni.navigateTo({
    url: `${pages}?data=${encodeURIComponent(JSON.stringify(temp))}`,
  });
}

const handleAddTeacher = () => {
  if (teacherQrcode.value) {
    addVisible.value = true;
    return;
  }

  API.notStart({ course_id: course_id.value }).then((res: any) => {
    teacherQrcode.value = res.teacher;
    addVisible.value = true;
  })
}
</script>

<style scoped lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  color: $uni-text-color;
  background-color: #f8ecd8;
  font-family: xiaolai;

  .container {
    position: absolute;
    width: 37.5rem;
    top: 6rem;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    // overflow: auto;

    .course-table {
      position: relative;
      margin-top: 1rem;
      width: 34.3rem;
      height: 21.7rem;
      margin-left: 50%;
      transform: translateX(-50%);
      background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/tryCourseHome-days-background.png");
      background-size: contain;
      background-repeat: no-repeat;

      .day-info-container {
        position: absolute;
        top: 6.9rem;
        left: 1.6rem;
        right: 1.6rem;
        height: 9.7rem;
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        .stage {
          position: absolute;
          top: 3.2rem;
          left: 3.5rem;
          height: 0.7rem;
          right: 3.5rem;
          background: linear-gradient(to right, #c5ce71 0, #c5ce71 var(--progress), #fbefd5 var(--progress), #fbefd5 100%);
          z-index: -1;
        }

        .day-info {
          width: 7rem;
          height: 100%;
          display: flex;
          justify-content: space-between;
          /* 水平居中 */
          align-items: center;
          /* 垂直居中 */
          flex-direction: column;

          .day-progress {
            position: relative;
            width: 100%;
            aspect-ratio: 1;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            /* 水平居中 */
            align-items: center;
            /* 垂直居中 */
            background: conic-gradient(from 180deg, #c5ce71 0 var(--progress), #f9eedc 0 100.01%);

            .day-selected {
              position: absolute;
              width: 7.2rem;
              height: 7.2rem;
              border-radius: 50%;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              border: 0.2rem solid #ffaf00;
              box-sizing: border-box;
            }

            .day-progress-content {
              width: 5.8rem;
              aspect-ratio: 1;
              background-color: white;
              display: flex;
              justify-content: center;
              /* 水平居中 */
              align-items: center;
              /* 垂直居中 */
              flex-direction: column;
              border-radius: 50%;

              .day {
                font-size: 1.6rem;
                font-family: baloo;
                color: #AD7E78;

                &.active {
                  color: $uni-text-color;
                }
              }

              .progress {
                font-size: 1.1rem;
                font-family: xiaolai;
                color: #AD7E78;

                &.active {
                  color: $uni-text-color;

                }
              }
            }
          }

          .course-title {
            font-size: 1.4rem;
            font-family: xiaolai;
            color: $uni-text-color;
          }
        }
      }

      .des {
        position: absolute;
        top: 19.2rem;
        font-size: 1.2rem;
        font-family: xiaolai;
        color: $uni-text-color-grey;
        width: 100%;
        text-align: center;
      }

      .add-teacher {
        position: absolute;
        top: -0.4rem;
        right: -1rem;
        width: 5.4rem;
        height: 3.1rem;
      }
    }

    .course-list-header {
      position: relative;
      margin-top: 2rem;
      display: flex;
      flex-direction: row;
      align-items: center;

      .current-day {
        position: relative;
        margin-left: 2rem;
        font-family: baloo;
        color: $uni-text-color;
        font-size: 1.8rem;
        // background-color: blue;
      }

      .current-day::before {
        content: "";
        position: absolute;
        left: -0.5rem;
        top: 0.5rem;
        width: 4.8rem;
        height: 1.7rem;
        background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/tryCourseHome-doodle.png");
        background-size: contain;
        background-repeat: no-repeat;
        z-index: -1;
      }

      .current-progress {
        margin-left: 1.2rem;
        font-family: xiaolai;
        font-size: 1.2rem;
        color: $uni-text-color-grey;
      }
    }

    .course-list-container {
      height: calc(100% - 28.1rem);
      width: 100%;
      overflow: auto;

      .course-container {
        position: relative;
        margin: auto;
        margin-top: 0.8rem;
        width: 34.3rem;
        height: 7.8rem;
        border: 0.2rem solid #cf9c49;
        box-sizing: border-box;
        border-radius: 1.2rem;
        background-color: white;

        .course-title {
          position: absolute;
          left: 2rem;
          top: 1.9rem;
          font-size: 1.7rem;
          line-height: 1.9rem;
        }

        .course-index {
          position: absolute;
          left: 2rem;
          top: 4.4rem;
          font-size: 1.2rem;
          line-height: 1.8rem;
          color: $uni-text-color-grey;
        }

        .course-status {
          position: absolute;
          right: 2rem;
          top: 50%;
          transform: translateY(-50%);
          width: 7rem;
          height: 2.4rem;
          display: flex;
          align-items: center;
          justify-content: center;
          // margin: 0;
          font-family: xiaolai;
          font-size: 1.4rem;
          border-radius: 1.2rem;
          box-sizing: border-box;
        }

        .course-lock {
          position: absolute;
          right: 2rem;
          top: 50%;
          transform: translateY(-50%);
          width: 2.2rem;
          height: 2.2rem;
        }

        .start {
          color: $uni-text-color;
          background-color: #FFE5B8;
          border: 0.1rem solid $uni-text-color;
        }

        .finish {
          color: #979797;
          border: 0.1rem solid #979797;
        }

        .learn {
          color: $uni-text-color;
          background-color: #C5CE71;
          border: 0.1rem solid $uni-text-color;
        }
      }
    }

    .operate-button {
      position: absolute;
      bottom: 2.5rem;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      width: 31.5rem;
      height: 5rem;
      margin: 0;
      border-radius: 1rem;
      color: $uni-text-color;
      font-family: xiaolai;
      font-size: 1.7rem;
      border: 2px solid $uni-btn-border;
      background-color: $uni-btn-prime;

      .operate-button-right {
        width: 1.2rem;
        height: 1.2rem;
      }
    }

    .is-hover {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}

.add-teacher-container {
  position: relative;
  width: 100%;

  .teacher-header {
    position: absolute;
    top: -9.5rem;
    left: 50%;
    width: 31.928rem;
    height: 14.283rem;
    transform: translateX(-50%);
    z-index: 1;
  }

  .teacher-content {
    width: 28rem;
    height: 31.6rem;
    margin-bottom: 3rem;
    margin-left: 50%;
    transform: translateX(-50%);
    background-size: contain;
    background-repeat: round;
    background-image: url("https://rwstatic.tentons.cn/web/Lesson/images/add-teacher-content.png");

    .teacher-line {
      width: 26.1rem;
      padding-top: 5.6rem;
      margin-left: 50%;
      margin-bottom: 1.5rem;
      transform: translateX(-50%);
      border-bottom: 1px dashed #EFDAB7;
    }

    .teacher-qrcode {
      width: 16.5rem;
      height: 16.5rem;
      margin-bottom: 1.5rem;
      margin-left: 50%;
      transform: translateX(-50%);
      border-radius: 1.2rem;
    }

    .teacher-label {
      display: block;
      line-height: 2rem;
      font-family: xiaolai;
      font-size: 1.3rem;
      color: $uni-text-color;
      text-align: center;
    }
  }

  .teacher-quit {
    position: relative;
    display: inline-block;
    margin-left: 50%;
    transform: translateX(-50%);
    font-family: xiaolai;
    font-size: 1.5rem;
    color: #E1E1E1;
    text-align: center;

    &::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      border-bottom: 1px solid #E1E1E1;
    }
  }
}
</style>
